package com.ludomancy.gamelib;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Window;
import java.util.Stack;

public class Utils
{
	private static Stack translationStack = new Stack();
	private static Stack clipStack = new Stack();
	private static int translateX, translateY;
	
	public static void pushClipStack(Graphics g)
	{
		Rectangle area = g.getClipRect();
		if(area == null)
		{
			area = new Rectangle(0, 0, GameCanvas.screen.getWidth(), GameCanvas.screen.getHeight());
		}
		clipStack.push(area);
	}
	
	public static void popClipStack(Graphics g)
	{
		Rectangle clip = (Rectangle) clipStack.pop();
		g.setClip(clip.x, clip.y, clip.width, clip.height);
	}
	
	public static void pushTranslation()
	{
		translationStack.push(new Point(translateX, translateY));
		translateX = translateY = 0;
	}
		
	public static void translate(Graphics g, int x, int y)
	{
		translateX += x;
		translateY += y;
		g.translate(x,y);
	}
	
	public static void popTranslation(Graphics g)
	{
		Point old = (Point) translationStack.pop();
		g.translate(-translateX, -translateY);
		translateX = old.x;
		translateY = old.y;
	}
	
    public static Point getCenterInRect(Point box, Rectangle area)
    {
    	int px = area.x + (area.width - box.x)/2;
    	int py = area.y + (area.height - box.y)/2;
    	Point ret = new Point(px,py);
    	return ret;
    }
    
    public static Point stringSize(Graphics g, String text)
    {
    	return new Point(g.getFontMetrics().stringWidth(text), g.getFontMetrics().getHeight());
    }
    
    public static void centerWindow(Window w)
	{
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension frameSize = w.getSize();

		if (frameSize.height > screenSize.height)
			frameSize.height = screenSize.height;
		if (frameSize.width > screenSize.width)
			frameSize.width = screenSize.width;
		w.setLocation((screenSize.width - frameSize.width) / 2,
				(screenSize.height - frameSize.height) / 2);
	}
    
    public static void drawString(Graphics g, String text, int x, int y)
    {
    	int offset = g.getFontMetrics().getHeight() - g.getFontMetrics().getDescent();
    	g.drawString(text, x, offset + y);
    }
    
    public static void drawStringVerticallyCentered(Graphics g, String text, int x, int centerY)
    {
    	//TODO: fix this hideous implementation
        int startY = centerY + g.getFontMetrics().getAscent()/2;
        g.drawString(text, x, startY );
    }    
}
